import { PlusIcon } from '@/components/bs-icons/plus'
import { Button } from '@/components/bs-ui/button'
import { useToast } from '@/components/bs-ui/toast/use-toast'
import { getFlowVersions } from '@/controllers/API/flow'
import { useDiffFlowStore } from '@/store/diffFlowStore'
import { FlowVersionItem } from '@/types/flow'
import { ChevronLeftIcon } from '@radix-ui/react-icons'
import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import Component from './components/Component'
import RunTest from './components/RunTest'

export default function DiffFlowPage(params) {
  // 技能 id, 版本id, 组件id
  const { id, vid, cid } = useParams()
  const navigate = useNavigate()
  const { message } = useToast()

  const versions = useVersions(id)

  const { mulitVersionFlow, removeVersionFlow, initFristVersionFlow, addEmptyVersionFlow, addVersionFlow } =
    useDiffFlowStore()
  useEffect(() => {
    initFristVersionFlow(vid)
  }, [])

  const handleAddVersion = () => {
    if (mulitVersionFlow.length >= 4) {
      return message({
        title: '',
        description: '最多添加4个版本',
        variant: 'error'
      })
    }
    addEmptyVersionFlow()
  }

  console.log('mulitVersionFlow', mulitVersionFlow)

  return (
    <div className="relative h-full bg-gray-100">
      {/* header */}
      <div className="absolute top-0 flex h-14 w-full items-center justify-between border-b bg-[#fff] px-4">
        <Button variant="outline" size="icon" onClick={() => navigate(-1)}>
          <ChevronLeftIcon className="h-4 w-4" />
        </Button>
        <span>版本评估</span>
        <Button type="button" onClick={handleAddVersion}>
          <PlusIcon className="text-primary" />
          添加版本({mulitVersionFlow.length}/4)
        </Button>
      </div>

      {/* content */}
      <div className="h-full overflow-y-auto pt-14">
        {/* comps */}
        <div
          className={`mt-4 box-border grid gap-4 px-4 ${mulitVersionFlow.length === 3 ? 'grid-cols-3' : 'grid-cols-2'}`}
        >
          {mulitVersionFlow.map((version, index) => (
            <Component
              key={index}
              compId={cid}
              options={versions}
              disables={mulitVersionFlow.map(v => v?.id)}
              version={version}
              className={''}
              onChangeVersion={vid => addVersionFlow(vid, index)}
              onClose={() => removeVersionFlow(index)}
            />
          ))}
        </div>
        {/* run test */}
        <RunTest nodeId={cid}></RunTest>
      </div>
    </div>
  )
}

const useVersions = flowId => {
  const [versions, setVersions] = useState<FlowVersionItem[]>([])
  useEffect(() => {
    getFlowVersions(flowId).then(({ data }) => {
      setVersions(data)
    })
  }, [])

  return versions
}
